package jwt_token

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"social-app/config"
	"time"
)

type User struct {
	UserId   int       `json:"user_id"`
	Username string    `json:"username"`
	Time     time.Time `json:"time"`
}

type Claims struct {
	User
	jwt.StandardClaims
}

func Encode(user User) (string, error) {
	// 设置token过期时间
	expirationTime := config.JwtConfig.Timeout
	// 创建声明
	claims := &Claims{
		User: user,
		StandardClaims: jwt.StandardClaims{
			// 过期时间
			ExpiresAt: expirationTime.Unix(),
			// 发行人
			Issuer: "example.com",
		},
	}
	// 创建token对象，使用HS256算法签名
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 生成token字符串
	tokenString, err := token.SignedString(config.JwtConfig.Key)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func Decode(token string) (*Claims, error) {
	claims := &Claims{}

	// 解析token
	tkn, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
		return config.JwtConfig.Key, nil
	})

	if err != nil {
		return nil, err
	}

	if !tkn.Valid {
		panic("Token无效")
	}

	return claims, nil
}

func GetUserId(c *gin.Context) int {
	UserId, _ := c.Get("user_id")
	return cast.ToInt(UserId)
}
